package com.dennytech.tac.utils;

import java.io.IOException;
import java.io.OutputStream;

public class WatchedOutputStream extends OutputStream {
	public static interface Listener {
		void notify(int write);
	}

	public static final int DEFAULT_NOTIFY_BYTES = 0xFFF; // 4k
	private OutputStream stream;
	private int remains;
	private int notifyBytes;
	private Listener listener;

	public WatchedOutputStream(OutputStream instream) {
		this(instream, DEFAULT_NOTIFY_BYTES);
	}

	public WatchedOutputStream(OutputStream instream, int notifyBytes) {
		this.stream = instream;
		this.notifyBytes = notifyBytes;
	}

	@Override
	public void close() throws IOException {
		stream.close();
	}

	@Override
	public void flush() throws IOException {
		stream.flush();
	}

	@Override
	public void write(int oneByte) throws IOException {
		stream.write(oneByte);
		if (++remains > notifyBytes) {
			int sr = remains;
			remains = 0;
			if (listener != null)
				listener.notify(sr);
		}
	}

	@Override
	public void write(byte[] buffer, int offset, int count) throws IOException {
		stream.write(buffer, offset, count);
		remains += count;
		if (remains > notifyBytes) {
			int sr = remains;
			remains = remains % notifyBytes;
			if (listener != null)
				listener.notify(sr - remains);
		}
	}

	@Override
	public void write(byte[] buffer) throws IOException {
		write(buffer, 0, buffer.length);
	}

	public void setListener(Listener listener) {
		this.listener = listener;
	}
}
